import React, { Component } from "react";
import { connect } from "dva";
import {
  Form,
  Button,
  Radio,
  Steps,
  Icon,
  Table,
  Breadcrumb,
  Checkbox,
  Input,
  message
} from "antd";
import { Link } from "dva/router";
import Drawer from "../../components/Pro/drawer/drawer";
import { gup } from "../../utils/utils";

import {
  //taskAttendanceComattendgroupfixedSave, //新增考勤组-选择考勤类型-固定班制-新增
  // taskAttendanceComattendgroupfixedGetAddTemp, //新增考勤组-选择考勤类型-固定班制-获取周一到周日模板
  //taskAttendanceComattendgroupfixedUpdate, //新增考勤组-选择考勤类型-固定班制-修改
  taskAttendanceComAttendGroupInFirstStepAttendGroup, //新增考勤组-选择考勤类型-固定班制-详情
  taskAttendanceComAttendGroupSaveFirstStepAttendGroup, //新增或者修改考勤组-第一步-设置考勤类型和工作安排
  taskComShiftPage //获取班次分页查询
} from "../../services/api";

import "./ThiftManagement.less";

const FormItem = Form.Item;
const { Step } = Steps;
const weekend = {
  1: "星期一",
  2: "星期二",
  3: "星期三",
  4: "星期四",
  5: "星期五",
  6: "星期六",
  7: "星期日"
};
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 7 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
    md: { span: 10 }
  }
};

const selectedRowKeysall = ["1", "2", "3", "4", "5", "6", "7"];

const submitFormLayout = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 10, offset: 7 }
  }
};

const dataSource1 = [
  {
    key: "1",
    weekDay: "1",
    detail: "休息",
    option: "选择班次",
    shiftId: "",
    isRest: "1"
  },
  {
    key: "2",
    weekDay: "2",
    detail: "休息",
    option: "选择班次",
    shiftId: "",
    isRest: "1"
  },
  {
    key: "3",
    weekDay: "3",
    detail: "休息",
    option: "选择班次",
    shiftId: "",
    isRest: "1"
  },
  {
    key: "4",
    weekDay: "4",
    detail: "休息",
    option: "选择班次",
    shiftId: "",
    isRest: "1"
  },
  {
    key: "5",
    weekDay: "5",
    detail: "休息",
    option: "选择班次",
    shiftId: "",
    isRest: "1"
  },
  {
    key: "6",
    weekDay: "6",
    detail: "休息",
    option: "选择班次",
    shiftId: "",
    isRest: "1"
  },
  {
    key: "7",
    weekDay: "7",
    detail: "休息",
    option: "选择班次",
    shiftId: "",
    isRest: "1"
  }
];

@connect(state => ({
  profile: state.profile
}))
@Form.create()
export default class SelectionAttendanceType extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      open: false, //固定--添加班次
      attendType: "1",
      attendGroupId: gup("attendGroupId") || "",
      midAttendGroupId: gup("midAttendGroupId") || "",
      isFormal: gup("isFormal") || "",
      isFollowLegalHoliday: "0",
      comAttendGroupFixeds: dataSource1.map(val => {
        const obj = { ...val };
        return obj;
      }),
      selectedRowKeys: [],
      radioSelectedRows: {}, //当前选种的班次
      isinit: true, //是否是新增
      taskComShiftPage: [], //所有班次
      currentkey: "", //当前工作日的key
      defaultClick: false, //是否设置默认班次
      pagenav: {
        current: 1,
        pageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: total => `总共 ${total} 条`,
        onShowSizeChange: (current, pageSize) => {
          const pagenav = Object.assign({}, this.state.pagenav);
          pagenav.current = current;
          pagenav.pageSize = pageSize;
          this.setState({ pagenav });
          setTimeout(() => {
            this.bbdExampersonPage();
          });
        },
        onChange: (page, pageSize) => {
          const pagenav = Object.assign({}, this.state.pagenav);
          pagenav.current = page;
          pagenav.pageSize = pageSize;
          this.setState({ pagenav });
          setTimeout(() => {
            this.bbdExampersonPage();
          });
        },
        total: 0
      }
    };
  }

  /*
固定班制---设置出勤班次 */
  columns1 = [
    {
      title: "工作日",
      dataIndex: "weekDay",
      key: "2",
      render: text => {
        return weekend[text];
      },
      width: 100
    },
    {
      title: "班次详情",
      dataIndex: "detail",
      key: "3",
      render: text => {
        let val = text;
        if (text === "") {
          val = "休息";
        }
        return <div dangerouslySetInnerHTML={{ __html: val }} />;
      }
    },
    {
      title: "操作",
      dataIndex: "option",
      key: "4",
      render: (text, record) => {
        return (
          <div
            onClick={() => {
              this.setState({
                currentkey: record.key,
                open: true,
                defaultClick: false
              });
            }}
            style={{ color: "rgba(15,113,255,1)" }}
          >
            选择班次
          </div>
        );
      },
      width: 80
    }
  ];

  /* 选择班次--drawer */
  columns4 = [
    {
      key: "1",
      title: "班次名称",
      dataIndex: "shiftName",
      render: text => <a href="#">{text}</a>,
      width: 100
    },
    {
      key: "2",
      title: "出勤时间",
      dataIndex: "shiftRuleTime",
      render: text => {
        return <div dangerouslySetInnerHTML={{ __html: text }} />;
      }
    }
  ];

  componentDidMount() {
    // window.initialize = this.initializeMap;
    this.taskComShiftPage();
    this.taskAttendanceComAttendGroupInFirstStepAttendGroup();
  }

  taskAttendanceComAttendGroupSaveFirstStepAttendGroup = () => {
    const {
      attendType,
      midAttendGroupId,
      isFollowLegalHoliday = "0",
      attendGroupName,
      comAttendGroupFixeds,
      attendGroupId
    } = this.state;
    if (
      !comAttendGroupFixeds.some(val => {
        return val.isRest === "0";
      })
    ) {
      message.error("班次至少要有一次");
      return;
    }
    taskAttendanceComAttendGroupSaveFirstStepAttendGroup({
      attendType,
      midAttendGroupId,
      isFollowLegalHoliday,
      attendGroupName,
      attendGroupId,
      comAttendGroupFixeds: JSON.stringify(comAttendGroupFixeds)
    })
      .then(res => {
        console.log(
          res,
          "新增或者修改考勤组-第一步-设置考勤类型和工作安排-res"
        );
        this.props.history.push(
          `/attendancemanagement/choosewayattendance?attendGroupId=${
            res.data.attendGroupId
          }&midAttendGroupId=${res.data.midAttendGroupId}`
        );
      })
      .catch(err =>
        console.log(err, "新增或者修改考勤组-第一步-设置考勤类型和工作安排-err")
      );
  };

  //新增考勤组-选择考勤类型-固定班制-详情
  taskAttendanceComAttendGroupInFirstStepAttendGroup = () => {
    taskAttendanceComAttendGroupInFirstStepAttendGroup({
      attendGroupId: this.state.attendGroupId,
      isFormal: this.state.isFormal,
      midAttendGroupId: this.state.midAttendGroupId
    }).then(
      response => {
        console.log(
          response,
          "新增考勤组-选择考勤类型-固定班制-详情-taskAttendanceComAttendGroupInFirstStepAttendGroup-response"
        );

        if (!("comAttendGroupFixeds" in response.data)) {
          return null;
        }
        let comAttendGroupFixeds = JSON.parse(
          response.data.comAttendGroupFixeds
        );

        const {
          attendType,
          midAttendGroupId,
          isFollowLegalHoliday,
          attendGroupName
        } = response.data;
        this.setState({
          attendType,
          midAttendGroupId,
          isFollowLegalHoliday,
          attendGroupName
        });

        const { setFieldsValue } = this.props.form;
        setFieldsValue({
          attendType,
          attendGroupName,
          isFollowLegalHoliday: isFollowLegalHoliday === "1" ? !0 : false
        });

        if (comAttendGroupFixeds.length > 0) {
          const selectedRowKeys = [];
          comAttendGroupFixeds = comAttendGroupFixeds.map(val => {
            val.key = val.weekDay + "";
            if (val.detail) {
              selectedRowKeys.push(val.weekDay + "");
            }
            return val;
          });
          this.setState(
            {
              isinit: false,
              comAttendGroupFixeds,
              selectedRowKeys
            },
            () => {
              this.setcomAttendGroupFixeds();
            }
          );
        } else {
          this.setState({
            isinit: true,
            comAttendGroupFixeds: dataSource1.map(val => {
              const obj = { ...val };
              return obj;
            })
          });
        }
      },
      err => {
        console.log(
          err,
          "新增考勤组-选择考勤类型-固定班制-详情-taskAttendanceComAttendGroupInFirstStepAttendGroup-err"
        );
      }
    );
  };
  //获取班次分页查询
  taskComShiftPage = () => {
    taskComShiftPage({
      pageSize: 5000,
      pageNumber: 1,
      shiftType: this.state.attendType
    }).then(
      response => {
        console.log(response, "获取班次分页查询-taskComShiftPage-response");
        const taskComShiftPagedata = response.data.data.map((val, i) => {
          val.key = i;
          return val;
        });
        this.setState({ taskComShiftPage: taskComShiftPagedata });
      },
      err => {
        console.log(err, "获取班次分页查询-taskComShiftPage-err");
      }
    );
  };

  //设置班次的值
  setbangchi = () => {
    console.log("aaa");
    const { comAttendGroupFixeds, radioSelectedRows, currentkey } = this.state;
    let { selectedRowKeys } = this.state;
    selectedRowKeys.push(currentkey);

    selectedRowKeys = Array.from(new Set(selectedRowKeys));
    comAttendGroupFixeds[currentkey - 1].detail = `${
      radioSelectedRows["shiftName"]
    }：${radioSelectedRows["shiftRuleTime"]}`;
    comAttendGroupFixeds[currentkey - 1].shiftId = radioSelectedRows["shiftId"];
    comAttendGroupFixeds[currentkey - 1].isRest = "0";

    this.setState({
      comAttendGroupFixeds,
      open: false,
      selectedRowKeys: selectedRowKeys.sort()
    });
  };
  //设置默认班次的值
  setbangchi1 = () => {
    console.log("setbangchi1");
    const { radioSelectedRows } = this.state;
    let { comAttendGroupFixeds } = this.state;

    comAttendGroupFixeds = selectedRowKeysall.map(val => {
      comAttendGroupFixeds[val - 1].detail = `${
        radioSelectedRows["shiftName"]
      }：${radioSelectedRows["shiftRuleTime"]}`;
      comAttendGroupFixeds[val - 1].shiftId = radioSelectedRows["shiftId"];
      comAttendGroupFixeds[val - 1].isRest = "0";
      return comAttendGroupFixeds[val - 1];
    });
    console.log(comAttendGroupFixeds, "setbangchi1", "comAttendGroupFixeds");
    this.setState({
      comAttendGroupFixeds,
      selectedRowKeys: ["1", "2", "3", "4", "5", "6", "7"],
      open: false
    });
  };

  //设置comAttendGroupFixeds 表单的值
  setcomAttendGroupFixeds = () => {
    const { comAttendGroupFixeds, isinit } = this.state;
    const { setFieldsValue } = this.props.form;
    const comAttendGroupFixeds1 = comAttendGroupFixeds.map(val => {
      const ob = {};
      ob.isRest = val.shiftId === "" ? "1" : "0";
      ob.weekDay = val.weekDay;
      ob.shiftId = val.shiftId;
      if (!isinit) {
        ob.attendGroupFixedId = val.attendGroupFixedId || "";
        ob.attendGroupId = val.attendGroupId || "";
      }
      return ob;
    });
    setFieldsValue({
      comAttendGroupFixeds: JSON.stringify(comAttendGroupFixeds1)
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    this.setcomAttendGroupFixeds();
    this.props.form.validateFieldsAndScroll((err, values) => {
      console.log(values, err, "values-handleSubmit");
      if (!err) {
        this.taskAttendanceComAttendGroupSaveFirstStepAttendGroup();
      }
    });
  };

  /* 固定上班次 */
  fixedShiftRender = () => {
    const { getFieldDecorator } = this.props.form;
    return (
      <FormItem {...formItemLayout} label="工作安排">
        {getFieldDecorator("comAttendGroupFixeds", {
          rules: [
            {
              required: true,
              message: "请选择"
            }
          ]
        })(
          <div>
            <Button
              onClick={() => {
                this.setState({ open: true, defaultClick: true });
              }}
              style={{ marginBottom: 16 }}
              type="primary"
              ghost
            >
              批量安排班次
            </Button>

            <Table
              size="middle"
              rowSelection={{
                onChange: (selectedRowKeys, selectedRows) => {
                  console.log(
                    `selectedRowKeys: ${selectedRowKeys}`,
                    "selectedRows: ",
                    selectedRows
                  );
                  const { comAttendGroupFixeds } = this.state;

                  selectedRowKeysall.forEach(val => {
                    if (selectedRowKeys.indexOf(val) === -1) {
                      comAttendGroupFixeds[val - 1].detail = "休息";
                      comAttendGroupFixeds[val - 1].shiftId = "";
                      comAttendGroupFixeds[val - 1].isRest = "1";
                    }
                  });
                  this.setState({
                    selectedRowKeys: selectedRowKeys.sort(),
                    comAttendGroupFixeds
                  });
                },
                getCheckboxProps: record => {
                  return {
                    disabled: record.isRest === "1" ? !0 : false // Column configuration not to be checked
                  };
                },
                selectedRowKeys: this.state.selectedRowKeys.filter(val => {
                  const { comAttendGroupFixeds } = this.state;
                  if (comAttendGroupFixeds[val - 1]) {
                    return comAttendGroupFixeds[val - 1].isRest === "0";
                  }
                  return false;
                })
              }}
              pagination={false}
              columns={this.columns1}
              dataSource={this.state.comAttendGroupFixeds}
            />
          </div>
        )}
      </FormItem>
    );
  };

  render() {
    const { submitting } = this.props;
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="CreateTask ThiftManagement">
        <div className="card-breadcrumb">
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/attendancemanagement/newattendanceunit">
                考勤组管理
              </Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>选择考勤类型</Breadcrumb.Item>
          </Breadcrumb>
        </div>
        <div className="card">选择考勤类型</div>
        <div className="Steps">
          <Steps current={0}>
            <Step title="选择考勤类型" />
            <Step title="考勤地点" />
            <Step title="设置考勤人员" />
            <Step title="完成" />
          </Steps>
        </div>
        <Form onSubmit={this.handleSubmit} style={{ marginTop: 24 }}>
          <FormItem {...formItemLayout} label="考勤组名称">
            {getFieldDecorator("attendGroupName", {
              initialValue: this.state.attendGroupName,
              rules: [
                {
                  required: true,
                  message: "请输入"
                },
                { max: 25, message: "已超出25个" }
              ]
            })(
              <Input
                onChange={e => {
                  this.setState({ attendGroupName: e.target.value });
                }}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="选择出勤类型">
            {getFieldDecorator("attendType", {
              initialValue: this.state.attendType,
              rules: [
                {
                  required: true,
                  message: "请选择"
                }
              ]
            })(
              <Radio.Group>
                <Radio className="radioStyle" value="1">
                  固定班制（每周考勤模式一致）
                  <span className="exclamation">
                    <Icon type="exclamation-circle" />适用于每周考勤固定的团队和部门。
                  </span>
                </Radio>
              </Radio.Group>
            )}
          </FormItem>
          {/* 固定班次 */}
          {this.fixedShiftRender()}
          <FormItem {...formItemLayout} label=" " colon={false}>
            {getFieldDecorator("isFollowLegalHoliday", {
              valuePropName: "checked"
            })(
              <Checkbox
                onChange={e => {
                  console.log(e, "e.target.value");
                  this.setState({
                    isFollowLegalHoliday: e.target.checked ? "1" : "0"
                  });
                }}
              >
                是否遵循法定假日
              </Checkbox>
            )}
          </FormItem>
          <FormItem {...submitFormLayout} style={{ marginTop: 24 }}>
            <Button
              onClick={() => {
                this.props.history.push(
                  "/attendancemanagement/newattendanceunit"
                );
              }}
              loading={submitting}
            >
              取消
            </Button>
            <Button type="primary" style={{ marginLeft: 8 }} htmlType="submit">
              确认并进行下一步
            </Button>
          </FormItem>
        </Form>
        {/* 固定班次--选择班次*/}
        <Drawer
          overlayColor="rgba(0, 0, 0,0)"
          right
          open={this.state.open}
          noTouchOpen
          noTouchClose
          width={600}
          className="drawer-box"
          onChange={open => {
            this.setState({ open });
          }}
        >
          <div className="drawer">
            <div className="drawer-header">
              选择默认班次
              {/* <Button type="primary" onClick={() => this.setState({ open3: true, open: false })} ghost>新增班次</Button> */}
            </div>
            <div className="drawer-content">
              <Table
                rowSelection={{
                  type: "radio",
                  onChange: (selectedRowKeys, radioSelectedRows) => {
                    console.log(
                      `selectedRowKeys: ${selectedRowKeys}`,
                      "radioSelectedRows: ",
                      radioSelectedRows
                    );
                    this.setState({ radioSelectedRows: radioSelectedRows[0] });
                  }
                }}
                pagination={false}
                columns={this.columns4}
                dataSource={this.state.taskComShiftPage}
              />
            </div>
            <div className="drawer-footer">
              <Button
                onClick={() => {
                  this.setState({
                    open: false
                  });
                }}
              >
                取消
              </Button>
              <Button
                onClick={() => {
                  console.log(
                    this.state.radioSelectedRows,
                    "this.state.radioSelectedRows"
                  );
                  if ("shiftTypeName" in this.state.radioSelectedRows) {
                    this.state.defaultClick
                      ? this.setbangchi1()
                      : this.setbangchi();
                  } else {
                    message.error("请选择班次");
                  }
                }}
                type="primary"
              >
                确定
              </Button>
            </div>
          </div>
        </Drawer>
      </div>
    );
  }
}
